const Service = require('egg').Service
const JWT = require('jsonwebtoken')

class UserService extends Service {
  // 注册接口
  async signup (signupMsg) {
    const { ctx } = this
    const res = {}
    const queryResult = await ctx.model.User.findOne({
      name: signupMsg.name
    })
    if (queryResult) {
      res.code = -1
      res.msg = '用户已存在'
    } else {
      const result = await ctx.model.User.create(signupMsg)
      res.data = result
      res.code = 1
      res.msg = '注册成功'
    }
    return res
  }

  // 登录接口
  async signin (signinMsg) {
    const { ctx } = this
    const res = {}
    const queryResult = await ctx.model.User.findOne({
      name: signinMsg.name
    })
    if (!queryResult) {
      res.code = -2
      res.msg = '用户不存在,请前去注册'
      res.data = {}
    } else {
      const result = await ctx.model.User.findOne(signinMsg)
      if (!result) {
        res.code = -1
        res.msg = '用户信息不正确'
        res.data = {}
      } else {
        const token = JWT.sign(
          {
            name: result.name
          },
          this.config.jwt.secret,
          {
            expiresIn: 60 * 60
          }
        )
        res.data = result
        res.code = 1
        res.msg = '登录成功'
        res.token = token
      }
    }
    return res
  }

  async signinWxchat ({ code }) {
    const { ctx } = this
    const sessionData = await ctx.service.wechatAuth.getInfoByCode({ code })
    // console.log('sessionData========', sessionData)
    const { session_key, openid } = sessionData
    let user = await ctx.model.User.findOne({ openid })
    // console.log('user======', user)
    if (!user) {
      user = await ctx.model.User.create({
        session_key,
        openid
        // mobile: `wx-xcx-${wechat.unionid}`,
        // password: randomize('*', 10), // unionid,
        // realName: wechat.nickName,
        // avatar: wechat.avatarUrl,
        // gender: wechat.gender == '1' ? '男' : '女',
        // wechatInfo: wechat
      })
      user = user.toJSON()
    }
    
    let jwtData = {
      userId: user._id,
      openid: openid
    }
    // if (user.roles) {
    //   jwtData.roles = user.roles
    // }
    console.log('jwtData========', jwtData)
    let token = await JWT.sign(jwtData, this.config.jwt.secret, {
      expiresIn: 60 * 60
    })
    // console.log('token=========', token)
    // user.token = token

    return {
      user,
      token
    }
  }

  // 查询用户信息
  async findUser (userMsg) {
    const { ctx } = this
    const res = {}
    const result = await ctx.model.User.findOne(userMsg)
    if (result) {
      res.data = result
      res.code = 1
      res.msg = '用户查询成功'
    } else {
      res.data = result
      res.code = -1
      res.msg = '该用户不存在'
    }
    return res
  }

  async updateUser (msg) {
    let res = {}
    const result = await this.ctx.model.User.findByIdAndUpdate(msg._id, msg)
    res.code = 1
    res.msg = '用户信息已更改'
    res.data = result
    return res
  }

  // 用户注销
  async logOff (userMsg) {
    const { ctx } = this
    const res = {}
    const result = await ctx.model.User.remove(userMsg)
    res.code = 1
    res.msg = '用户已注销'
    res.data = result
    return res
  }
  // 超级管理员删除用户
  async deleteUser (deleteUserMsg) {
    const { ctx } = this
    const res = {}
    const result = await ctx.model.User.remove(deleteUserMsg)
    res.code = 1
    res.msg = '用户已被删除'
    res.data = result
    return res
  }
}

module.exports = UserService
